/**
 *  线程同步例程：说明静态的和非静态的同步方法
 * */
package thread;

public class J_SynchronizedStatic extends Thread{
    public int m_ID;
    public J_Experiment2 m_data;
    public J_SynchronizedStatic(int id){
        m_ID = id;
    }

    @Override
    public void run() {
        System.out.println("运行线程："+m_ID);
        m_data.mb_methodSynchronized(m_ID);
        m_data.mb_methodStatic(m_ID);
        m_data.mb_method(m_ID);
    }

    public static void main(String args[]){
        int n =10;
        J_SynchronizedStatic[] t = new J_SynchronizedStatic[n];
        J_Experiment2 d = new J_Experiment2();
        for (int i = 0; i < n; i++) {
            t[i] = new J_SynchronizedStatic(i);
            t[i].m_data =d;
            t[i].start();
        }
        System.out.println("方法main结束");
    }
}

class J_Experiment2 {
    public static void mb_sleep(long millis){
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            System.out.println("异常 InterruptedException："+e);
            e.printStackTrace();
        }
    }

    public static synchronized void mb_methodStatic(int id){
        System.out.printf("线程 %1$d 进入静态同步方法\r\n",id);
        mb_sleep(1000);
        System.out.printf("线程 %1$d 离开静态同步方法\r\n",id);
    }

    public synchronized void mb_methodSynchronized(int id){
        System.out.printf("线程 %1$d 进入非静态同步方法\r\n",id);
        mb_sleep(1000);
        System.out.printf("线程 %1$d 离开非静态同步方法\r\n",id);
    }

    public void mb_method(int id){
        System.out.printf("线程 %1$d 进入非静态非同步方法\r\n",id);
        mb_sleep(1000);
        System.out.printf("线程 %1$d 离开非静态非同步方法\r\n",id);
    }
}
